const Koa = require('koa')
const router = require('./routes/index')
const static = require('koa-static')
const path = require('path')
const parser = require('koa-bodyparser')
const views = require('koa-views')
const jwt = require('jsonwebtoken')
const cors = require('@koa/cors')
const app = new Koa()
app.use(parser())

app.use(static(path.join(__dirname, 'public')))
app.use(views(path.join(__dirname, 'views'), { extension: 'ejs' }))
app.use(cors())

app.use((ctx, next) => {
  //如果是登录页或者api直接放行
  if (ctx.url.includes('/login') || ctx.url.includes('/api')) {
    next()
    return
  }
  let token = ctx.get('authorization')
  //判断有没有token，有就验证是否过期，未过期再设置一次更新过期时间，没有token就返回403未登录
  if (token) {
    let flag = jwt.verify(token, 'xujiawei')
    console.log(flag)
    if (flag) {
      let newtoken = jwt.sign({ username: 'lisi' }, 'xujiawei', { expiresIn: '1d' })
      ctx.set('authorization', newtoken)
      next()
    } else {
      ctx.status = 401
      ctx.body = 'token过期'
    }
  } else {
    ctx.status = 403
    ctx.body = '未登录'
  }
})
app.use(router.routes()).use(router.allowedMethods())

app.listen(3000, () => {
  console.log('koa is running')
})
